import Vue from 'vue'
import moment from 'moment'
let that=Vue.prototype;

let friendlyDate =function(timestamp) {
    let now = new Date();
    let leftTime=now.getTime()-timestamp;
    let leftsecond = parseInt(leftTime/1000);
    let day = Math.floor(leftsecond/(60*60*24));
    let hour = Math.floor((leftsecond-day*24*60*60)/3600);
    let minute = Math.floor((leftsecond-day*24*60*60-hour*3600)/60);
    let second = Math.floor(leftsecond-day*24*60*60-hour*3600-minute*60);
    let result=day+"天"+hour+"时"+minute+"分"+second+"秒";
    return  result;
}

let floatFilter =function(value) {
    if (typeof(value)=="number"){
        let realVal = parseFloat(value).toFixed(2);
        return realVal;
    }
    return null;
}


let initTableHead=function (tableHead) {
    for (let tableHeadKey in tableHead.rows) {
        tableHead.rows[tableHeadKey].index=parseInt(tableHeadKey);//设置排序值
    }
    //存储默认值 HEAD_DEFAULT_
    let storage=window.localStorage;
    storage.setItem("HEAD_DEFAULT_"+tableHead.code,JSON.stringify(tableHead));

    //获取用户设置的值 HEAD_
    let storageTableHead=storage.getItem("HEAD_"+tableHead.code);
    if (storageTableHead!=null) {
        let headData = JSON.parse(storageTableHead);
        tableHead = headData;
    }else{
        that.$http.post('/tableHeader/getTableHeader/'+tableHead.code).then(function(res){
            if(res.data.success){
                if (res.data.data!=null){//服务器如果有配置，则读取服务器的配置
                    tableHead=res.data.data;
                }else{
                    console.log("服务器无此表头的数据");
                }
            }else{
                that.$message.error('操作错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
            }
        },function(){
            //that.$message.error('操作错误！');
            console.error("请求数据错误");
        });
    }
    initTableHeadFormat(tableHead);
    return tableHead;
}

let initTableHeadFormat=function(tableHead){
    //解析 formatter
    for (let tableHeadKey in tableHead.rows) {
        //排序列
        tableHead.rows[tableHeadKey].index=parseInt(tableHeadKey);//设置排序值

        if(tableHead.rows[tableHeadKey].formatType==='float'){//float类型
            tableHead.rows[tableHeadKey].formatter=function (row, column,cellValue) {
                return floatFilter(cellValue);
            }
        }else if(tableHead.rows[tableHeadKey].formatType==='datetime'){//时间类型

            tableHead.rows[tableHeadKey].formatter=function (row, column,cellValue) {
                if (cellValue!=null && cellValue>0){
                    let timeStr= moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
                    return timeStr;
                }else if (cellValue===-62135798400000){
                    return "";
                }else{
                    return cellValue;
                }
            }
        }else{//其他类型 直接返回值
            tableHead.rows[tableHeadKey].formatter=function (row, column,cellValue) {
                return cellValue;
            }
        }
    }
}

let batchAddGoods=function (selectGoods,goodsList) {
    let _successNum=0;
    let _failNum=0;
    for (let key in selectGoods) {
        let goods=selectGoods[key];
        let flag=false;
        for (let i in goodsList) {
            let _goods=goodsList[i];
            if (_goods.id===goods.id){
                flag=true;
                break;
            }
        }
        if (!flag){
            that.$set(goods,'goodsQty', 1);
            that.$set(goods,'discountAmt', 0);
            that.$set(goods,'itemAmt', 0);
            that.$set(goods,'goodsID', goods.id);
            //that.$set(goods,'id', null);
            goodsList.push(goods);
            //this.recalculate(goods);
            _successNum++;
        }else{
            _failNum++
        }
    }
    that.$message({ type: 'success',message: '成功添加'+_successNum+'个商品，'+_failNum+'个商品已存在', showClose: true,});
}

let batchAddItemGoods=function (selectGoods,itemList) {
    console.log(itemList);

    let _successNum=0;
    let _failNum=0;
    for (let key in selectGoods) {
        let goods=selectGoods[key];
        let flag=false;
        for (let i in itemList) {
            let item=itemList[i];
            if (Number(item.goodsID)===Number(goods.id)){
                flag=true;
                break;
            }
        }
        if (!flag){
            console.log("add goods.id "+goods.id+" key "+key);
            let _goods=JSON.parse(JSON.stringify(goods));
            that.$set(_goods,'goodsQty', Number(1));
            that.$set(_goods,'discountAmt', Number(0));
            that.$set(_goods,'itemAmt', Number(0));
            that.$set(_goods,'goodsID', Number(_goods.id));
            that.$set(_goods,'id', null);
            itemList.push(_goods);
            _successNum++;
        }else{
            _failNum++
        }
    }
    that.$message({ type: 'success',message: '成功添加'+_successNum+'个商品，'+_failNum+'个商品已存在', showClose: true,});
}

let batchDeleteGoods=function (selectGoods,goodsList) {
    for (let key in selectGoods) {
        let goods=selectGoods[key];
        for (let i in goodsList) {
            let _goods=goodsList[i];
            if (_goods.id===goods.id){
                goodsList.splice(i,1);
                break;
            }
        }
    }
    that.$message({ type: 'success',message: '成功删除商品', showClose: true,});
}

let batchDeleteGoodsItem=function (selectItemList,itemList) {
    for (let key in selectItemList) {
        let selectItem=selectItemList[key];
        for (let i in itemList) {
            let item=itemList[i];
            if (item.goodsID===selectItem.goodsID){
                itemList.splice(i,1);
                break;
            }
        }
    }
    that.$message({ type: 'success',message: '成功删除商品', showClose: true,});
}

let canSelectAll=function(_this,selectionArray,pageSize,totalSize){
    //let _this=this;
    if (selectionArray.length>0 && (selectionArray.length === pageSize)){
        //alert(9999);
        _this.$confirm('请确定选择范围?', '全选提示', {
            confirmButtonText: '所有符合数据[' + totalSize + ']条',
            cancelButtonText: '当前页数据[' + selectionArray.length + ']条',
            type: 'warning'
        }).then(() => {
            _this.isSelectAll =true;
        }).catch(() => {
            _this.isSelectAll =false;
        });
    }else{
        _this.isSelectAll =false;
    }
}
//获得兄弟节点列表
let getBrotherNodeList=function(nodeList, id){
    let res;
    for(let i in nodeList){
        let node =nodeList[i];
        if (node.id===id){
            return nodeList;
        }
        if (typeof(node.children)!=='undefined' && node.children.length>0) {
            res = this.getBrotherNodeList(node.children, id);
            if (res) {
                return res;
            }
        }
    }
    return null;
}

let selectionPost=function(_this,multipleSelection,confirmText,url,params,successFun,errorFun){
    if(multipleSelection.length===0){
        _this.$message({showClose: true,message: '请选择要操作的数据', type: 'warning' });
    }else {
        _this.$confirm(confirmText, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //删除数据
            _this.$http.post(url,params).then(function(res){
                if(res.data.success){
                    _this.$message({ type: 'success',message: '操作成功～' });
                    successFun(res.data);
                }else{
                    _this.$message.error('操作错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                    errorFun(res.data);
                }
            },function(){
                _this.$message.error('操作错误！');
                errorFun(null);
            });
        });
    }
}

let singleSelectionPost=function(_this,multipleSelection,confirmText,url,params,successFun,errorFun){
    if(multipleSelection.length===0){
        _this.$message({showClose: true,message: '请选择要操作的数据', type: 'warning' });
    }else if(multipleSelection.length>1){
        _this.$message({showClose: true,message: '只能选择一条数据', type: 'warning' });
    }else {
        _this.$confirm(confirmText, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //删除数据
            _this.$http.post(url,params).then(function(res){
                if(res.data.success){
                    _this.$message({ type: 'success',message: '操作成功～' });
                    successFun(res.data);
                }else{
                    _this.$message.error('操作错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                    errorFun(res.data);
                }
            },function(){
                _this.$message.error('操作错误！');
                errorFun(null);
            });
        });
    }
}

let singleSelection=function(_this,multipleSelection,openFun){
    if(multipleSelection.length===0){
        _this.$message({showClose: true,
            message: '请选择要操作的数据',
            type: 'warning'
        });
    }else if(multipleSelection.length>1){
        _this.$message({showClose: true,message: '只能选择一条数据', type: 'warning' });
    }else {
        //_this.editVisible=true;
        setTimeout(function(){
            openFun();
        }, 50);
    }
}

/*let loadTableData=function(_this,url,params){
    _this.$http.post(url,params).then(function(res){
        if(res.data.success){
            _this.tableData=res.data.data;
            _this.loading=false;
        }else{
            _this.$message.error('获取数据错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
        }
        _this.loading=false;
    },function(){
        _this.$message.error('获取数据错误！');
        _this.loading=false;
    });
}*/


let loadFormData=function(_this,url,successCallback){
    setTimeout(function(){
        _this.$http.post(url).then(function(res){
            if(res.data.success){
                //_this.form=res.data.data;
                successCallback(res.data.data);
            }else{
                _this.$message.error('操作失败！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
            }
        },function(){
            _this.$message.error('操作失败！');
        });
    }, 100);
}

let submitFormData =function (_this,formRef,url,params,preValidate,successCallback) {
    formRef.validate((valid) => {
        valid=preValidate(valid);
        if (valid) {
            _this.$http.post(url,params).then(function(res){
                if(res.data.success){
                    _this.$message({ type: 'success',message: '操作成功～' });
                    successCallback(res.data.data);
                }else{
                    _this.$message.error('操作失败！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                }
            },function(e){
                _this.$message.error('操作失败'+e);
            });
        } else {
            return false;
        }
    });
};

let loadTableData=function(_this,url){
    _this.loading=true;
    _this.query.page=_this.tableData.page;
    _this.query.size=_this.tableData.size;
    _this.$http.post(url,_this.query).then(function(res){
        if(res.data.success){
            _this.tableData=res.data.data;
            _this.loading=false;
        }else{
            _this.$message.error('获取数据错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
        }
        _this.loading=false;
    },function(e){
        _this.$message.error('获取数据错误！'+e);
        _this.loading=false;
    });
};

let ajaxValidate =function(_this,url,params,value,callback){
    if (value != "") {
        _this.$http.post(url,params).then(function(res){
            if(res.data.success){
                let flag=res.data.data;
                if (flag){
                    callback();
                }else{
                    callback(new Error("数据重复，请重新选择"));
                }
            }else{
                _this.$message.error('获取数据失败,失败原因：'+res.data.msg);
                callback(new Error("验证失败"));
            }
        },function(){
            _this.$message.error('获取数据失败！');
            callback(new Error("验证失败"));
        });

    } else {
        callback(new Error("请输入数据"));
    }
}



let resetTableHeight = function(_this,clientHeight){ //监听屏幕高度变化
    setTimeout(function (){
        _this.dataTableHeight = clientHeight - _this.$refs.tableRef.$el.offsetTop - 50;
    },200)
}

let byteToString = function(limit){
    let size = "";
    if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
    }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
    }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
    }else{ //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }

    let sizeStr = size + "";
    let len = sizeStr.indexOf("\\.");
    let dec = sizeStr.substr(len + 1, 2);
    if(dec == "00"){//当小数点后为00时 去掉小数部分
        return sizeStr.substring(0,len) + sizeStr.substr(len + 3,2);
    }
    return sizeStr;
}



export default {
    friendlyDate,
    floatFilter,
    initTableHead,
    batchAddGoods,
    batchAddItemGoods,
    batchDeleteGoods,
    batchDeleteGoodsItem,
    canSelectAll,
    getBrotherNodeList,
    initTableHeadFormat,

    selectionPost,
    singleSelectionPost,
    singleSelection,
    loadTableData,
    loadFormData,
    submitFormData,
    resetTableHeight,
    ajaxValidate,
    byteToString,

}

